package com.aspire.nm.component.cmppserver.filter;


import javax.annotation.Resource;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Service;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppConnectPacket;
import com.aspire.nm.component.cmppserver.filter.coder.packet.Version;
import com.aspire.nm.component.cmppserver.runTime.SysRunTimeService;
import com.aspire.nm.component.cmppserver.util.LogService;

@Service
public class CmppFilter extends IoFilterAdapter {
	
	
	
	@Resource
	private LogService logService;
	@Resource
	private SysRunTimeService sysRunTimeService;
    
    public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    	if(message instanceof CmppConnectPacket){
    		if(sysRunTimeService.isConnected(session)){
    			logService.reSendCmppConnectPacket(session);
    			sysRunTimeService.getForbiddenCmppCount().increment();
    		}else{
    			if(Version.UNKNOW_VERSION.equals(((CmppConnectPacket)message).getVersion())){
    				logService.versionErr(session);
    				sysRunTimeService.getForbiddenCmppCount().increment();
    				session.close(true);
    			}else{
    				nextFilter.messageReceived(session, message);
    			}
    		}
    	}else if(!sysRunTimeService.isConnected(session)){
    		logService.sendCmppPacketWithUnConnected(session);
    		sysRunTimeService.getForbiddenCmppCount().increment();
    		session.close(true);
    	}else{
    		nextFilter.messageReceived(session, message);
    	}
    }

	
}

